package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.SystemMenu;
import cn.wolfcode.crm.mapper.SystemMenuMapper;
import cn.wolfcode.crm.query.ObjectQuery;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.service.ISystemMenuService;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class SystemMenuServiceImpl implements ISystemMenuService {
    @Autowired
    private SystemMenuMapper systemMenuMapper;

    public void save(SystemMenu systemMenu) {
        systemMenuMapper.save(systemMenu);
    }

    public void delete(Long id) {
        systemMenuMapper.delete(id);

    }

    public void update(SystemMenu systemMenu) {
        systemMenuMapper.update(systemMenu);
    }

    public SystemMenu get(Long id) {
        return systemMenuMapper.get(id);
    }

    public List<SystemMenu> getAll() {

        return systemMenuMapper.getAll();
    }

    public PageResult<SystemMenu> query(ObjectQuery qo) {
        int totalCount = systemMenuMapper.queryForCount(qo);
        if (totalCount == 0) {
            return new PageResult<SystemMenu>(0, Collections.EMPTY_LIST);
        }

        List<SystemMenu> list = systemMenuMapper.queryForList(qo);

        return new PageResult<SystemMenu>(totalCount,list);
    }

    public List<Map> selectMenuByParentSn(String parentSn) {
//        Employee employee = UserContext.getEmployeeAttribute();
      // if (employee.isAdmin()) {

        //获取当前的登陆的用户, 然后把id传入, 然后根据它的id查询所有菜单
        Employee employee = UserContext.getEmployeeInSession();

        if (employee==null || employee.isAdmin()){
            return systemMenuMapper.selectMenuByParentSn(parentSn);
        }else{
            return systemMenuMapper.selectMenuByParentSnAndEmployeeId(parentSn,employee.getId());
        }

       // }
//        return systemMenuMapper.selectMenuByParentSnAndEmployeeId(parentSn, employee.getId());

    }

    public List<SystemMenu> queryRootMenu() {
        return systemMenuMapper.queryRootMenu();
    }

    public PageResult<SystemMenu> queryMenusByRoleId(Long roleId) {
        List<SystemMenu> menus = systemMenuMapper.queryMenusByRoleId(roleId);
        return new PageResult<>(menus.size(),menus);

    }

}
